/*
 * @Author: fengwei fengwei029@foxmail.com
 * @Date: 2023-05-10 09:08:21
 * @LastEditors: fengwei fengwei029@foxmail.com
 * @LastEditTime: 2023-05-10 09:35:23
 * @FilePath: \KT\面试题\JS\write-code\k-mostChar.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/**
 * @description 取出前k位高频出现的元素
 */

type MostChar = {
    char: string;
    num: number;
}

function getMostCharFromString(str:string, k:number = str.length): MostChar{
    const result: MostChar = {
        char: '',
        num: 0
    }
    
    if(k > str.length){
        k = str.length;
    }

    let i = 0;
    let j = 0;
    let tempLength = 0;

    for(; i < k; i++) {
        if(str[i] === str[j]){
            tempLength++;
        } else {
            if(tempLength > result.num) {
                result.char = str[j];
                result.num = tempLength;
            }
            tempLength = 0;
            if(i < k-1){
                j = i;
                i--;
            }
            
        } 
    }

    return result;
}

// 功能测试
const str = 'abbcccddddee';
const res: MostChar = getMostCharFromString(str, 17);
console.log(res);